package com.cmcc.aregister.cs.constant;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.httpclient.params.HttpConnectionManagerParams;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.params.ConnRoutePNames;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.util.Log;

import com.cmcc.aregister.cs.util.Utils;

public class ConfigUtil {
	private static final String TAG = "ConfigUtil";
	public static boolean debug = false;
	public static String url = "http://219.136.91.63:19983/cm/powerManager/httponepay.pay";//银联支付请求报文的地址（统一支付）
	
	public static String payUrlPre = "http://219.136.91.63:19983/cm/powerManager/touchsimple/onepay.pay";//小额支付请求的地址（统一支付）
	public static String backUrl = "http://wap.szicity.com/cm/yiliao/wuxian/index.php?c=main&a=payreturn";//支付回跳URL
	/**
	 * 频道SP_ID：sp0001M000092 
频道SP密码：666666
频道业务代码：sp0001M000092 
商户编号：888888888
外部商户号：M000092  
	 */
	public static String spID = "sp0001M000108";//频道SP_ID,由本平台提供
	public static String spPwd = "666666";//频道SP密码,由本平台提供
	public static String spCode = "sp0001M000108";//频道业务代码,由本平台提供
	public static String spType = "0101";//频道操作类型
	public static String merchantCode = "88899999";//商户编号,由本平台提供
	public static String merchantName = "china_mobile";//商户名称
	public static String merchandise = "yygh";//订单名称
	public static String orderDesc = "小额支付";//订单描述
//	public static String orderDesc = "银联支付";//订单描述
	public static String payType = "1";//商品指定支付类型,1小额支付,2手机支付,3招行支付,4现场支付,5M值支付，8，银联支付。默认0或者空，则不指定支付方式
	public static String outMerchantCode = "M000110";//外部商户编号
	public static String spPay = "8";//支付类型
	
	public static String payVersion = "1_0";
	
//	public static String payAction = merchantName + "_" + outMerchantCode + "_" + payVersion;
	public static String payAction = "china_mobile_M000110_1_0";
	
	public static final int MEMBER_OPER_FLAG_UPD = 1;// 修改操作
	public static final int MEMBER_OPER_FLAG_ADD = 2;// 删除操作
	/**
	 * 得到现在时间
	 * 
	 * @return 字符串 yyyyMMdd HHmmss
	 */
	public static String getStringNow() {
		Date currentTime = new Date();
		SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
		String dateString = formatter.format(currentTime);
		return dateString;
	}
	/**
	 * 请求银联支付超时时间
	 * @return
	 */
	public static String getString10after() {
		Date currentTime = new Date();
		SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
		String dateString = formatter.format(currentTime);
		Long l = new Long(dateString);
		String after10Time = Long.toString((l + 1000));
		return after10Time;
	}
	/**
	 * 银联支付请求报文的请求
	 * @param timestamp
	 * @param timeout
	 * @param msg_id
	 * @param orderNo
	 * @param amount
	 * @param mobile
	 * @param targetMobile
	 * @return
	 */
	public static String postXml(String timestamp,
			String timeout,
			 String msg_id,
			 String orderNo,
			 String amount,
			 String mobile,
			 String targetMobile){
		StringBuffer sb = new StringBuffer();
		sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
		sb.append("<interfaceData>");
		sb.append("<spID>" + spID + "</spID>");
		sb.append("<spPwd>" + spPwd + "</spPwd>");
		sb.append("<spCode>" + spCode + "</spCode>");
		sb.append("<spType>" + spType + "</spType>");
		sb.append("<timestamp>" + timestamp + "</timestamp>");
		sb.append("<timeout>" + timeout + "</timeout>");
		sb.append("<merchantCode>" + merchantCode + "</merchantCode>");
		sb.append("<datas>");
		sb.append("<msg_id>" + msg_id + "</msg_id>");
		sb.append("<orderNo>" + orderNo + "</orderNo>");
		sb.append("<mobile>" + mobile + "</mobile>");
		sb.append("<targetMobile>" + targetMobile + "</targetMobile>");
		sb.append("<merchantName>" + merchantName + "</merchantName>");
		sb.append("<merchandise>" + merchandise + "</merchandise>");
		sb.append("<amount>" + amount + "</amount>");
		sb.append("<orderDesc>" + orderDesc + "</orderDesc>");
		sb.append("<payType>" + payType + "</payType>");
		sb.append("<outMerchantCode>" + outMerchantCode + "</outMerchantCode>");
		sb.append("<spPay>" + spPay + "</spPay>");
		sb.append("</datas>");
		sb.append("</interfaceData>");	
		if(debug){
			Log.i(TAG,"sb:" + sb.toString());
		}
		boolean sendOk = false;
		int resendCount = 2;
		int result = 0;		
		long nowDate = System.currentTimeMillis();
		PostMethod post = new PostMethod(url);
		String respData = new String();
		try {
			while ( !sendOk && resendCount < 3 ) {
				RequestEntity entity = new StringRequestEntity(sb.toString(), "text/xml", "UTF-8");				
				post.setRequestEntity(entity);
//				post.setRequestEntity(entity);
				HttpClient httpclient = new HttpClient();
				HttpConnectionManagerParams params = httpclient.getHttpConnectionManager().getParams(); 
				params.setConnectionTimeout(30*1000);
				params.setSoTimeout(60*1000);
				if (!Utils.isWifi()) {
					String proxyHost = android.net.Proxy.getDefaultHost();
					if (proxyHost != null) {// 如果是wap方式，要加网关
						System.out.println(proxyHost);
						HttpHost proxy = new HttpHost("10.0.0.172", 80);
						httpclient.getParams().setParameter(
								ConnRoutePNames.DEFAULT_PROXY, proxy);
					}
				}
				result = httpclient.executeMethod(post);
				if(debug){
					Log.i(TAG,"响应报文返回所用时间："+(System.currentTimeMillis()-nowDate));
				}
				if (result == 200) {					
					respData = post.getResponseBodyAsString();	
					if(debug){
						Log.i(TAG,"响应原始数据：" + respData);
					}
					sendOk = true;
				} else {	
					if(debug){
						Log.i(TAG,"result-->" + result);
					}
					resendCount++;
				}
			}

		} catch (Exception e) {
		} finally {
			post.releaseConnection();
		}
		if(debug){
			Log.i(TAG,"respData-->" + respData);
		}
		return respData;
	}
	static int timeoutConnection = 30 * 1000;
	static int timeoutSocket = 30 * 1000;
	
	/**
	 * 异地预约的post请求
	 * @param url
	 * @param map
	 * @return
	 */
	public static String requestOther(String url,Map<String,String> map){
		String resultData = "";
		HttpClient httpclient = new HttpClient();
		HttpConnectionManagerParams params = httpclient.getHttpConnectionManager().getParams(); 
		params.setConnectionTimeout(timeoutConnection);
		params.setSoTimeout(timeoutSocket);
		PostMethod post = new PostMethod(url);
		if (!Utils.isWifi()) {
			String proxyHost = android.net.Proxy.getDefaultHost();
			if (proxyHost != null) {// 如果是wap方式，要加网关
				System.out.println(proxyHost);
				HttpHost proxy = new HttpHost("10.0.0.172", 80);
				httpclient.getParams().setParameter(
						ConnRoutePNames.DEFAULT_PROXY, proxy);
			}
		}
		JSONObject json = new JSONObject();  
		try {
		List<NameValuePair> parameters = new ArrayList<NameValuePair>(); 
		if (map != null) {
			for (String key : map.keySet()) {
				parameters.add(new BasicNameValuePair(key, map.get(key)));  
				json.put(key, map.get(key));  
			}
		}
		String jsonStr = json.toString(); 
		if(ConfigUtilHelper.debug){
			Log.i(TAG,"jsonStr：" + jsonStr);
		}
		int result = 0;
			RequestEntity entity = new StringRequestEntity(jsonStr, "text/josn", "UTF-8");				
			post.setRequestEntity(entity);
			result = httpclient.executeMethod(post);
			if (result == 200){
				resultData = post.getResponseBodyAsString();	
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
		if(ConfigUtilHelper.debug){
			Log.i(TAG,"result：" + resultData);
		}
		return resultData;
	}
	
	
	/**
	 * 流量统计post请求
	 * @param url
	 * @param map
	 * @return
	 */
	public static String liuliangRequestPost(String url,Map<String,String> map,JSONObject j){
		String resultData = "0";
		HttpClient httpclient = new HttpClient();
		HttpConnectionManagerParams params = httpclient.getHttpConnectionManager().getParams(); 
		params.setConnectionTimeout(timeoutConnection);
		params.setSoTimeout(timeoutSocket);
		PostMethod post = new PostMethod(url);
		if (!Utils.isWifi()) {
			String proxyHost = android.net.Proxy.getDefaultHost();
			if (proxyHost != null) {// 如果是wap方式，要加网关
				System.out.println(proxyHost);
				HttpHost proxy = new HttpHost("10.0.0.172", 80);
				httpclient.getParams().setParameter(
						ConnRoutePNames.DEFAULT_PROXY, proxy);
			}
		}
		JSONObject json = new JSONObject();  
		try {
		List<NameValuePair> parameters = new ArrayList<NameValuePair>(); 
		if (map != null) {
			for (String key : map.keySet()) {
				if(ConfigUtilHelper.debug){
					Log.i(TAG,key + ":" + map.get(key));
				}
				parameters.add(new BasicNameValuePair(key, map.get(key)));  
				json.put(key, map.get(key)); 
			}
		}
		json.put("network", j);
		String jsonStr = json.toString(); 
		if(ConfigUtilHelper.debug){
			Log.i(TAG,"jsonStr：" + jsonStr);
		}
		int result = 0;
			RequestEntity entity = new StringRequestEntity(jsonStr, "text/josn", "UTF-8");				
			post.setRequestEntity(entity);
			result = httpclient.executeMethod(post);
			if (result == 200){
				resultData = post.getResponseBodyAsString();	
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
		if(ConfigUtilHelper.debug){
			Log.i(TAG,"result：" + resultData);
		}
		try {
			JSONObject jo = new JSONObject(resultData);
			return jo.getString("result");
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return resultData;
	}
	
	
	/**
	 * httppost请求
	 * @param url
	 * @param map
	 * @return
	 */
	public static String requestPost(String url,Map<String,String> map){
		String resultData = null;
		HttpParams httpParameters = new BasicHttpParams();
		HttpConnectionParams.setConnectionTimeout(httpParameters,timeoutConnection);
		HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);

		DefaultHttpClient client = new DefaultHttpClient(httpParameters); 

		HttpPost post = new HttpPost(url);  

		if (!Utils.isWifi()) {
			String proxyHost = android.net.Proxy.getDefaultHost();
			if (proxyHost != null) {// 如果是wap方式，要加网关
				System.out.println(proxyHost);
				HttpHost proxy = new HttpHost("10.0.0.172", 80);
				client.getParams().setParameter(
						ConnRoutePNames.DEFAULT_PROXY, proxy);
			}
		}
		try {
			List<NameValuePair> parameters = new ArrayList<NameValuePair>(); 
			if (map != null) {
				for (String key : map.keySet()) {
					if(ConfigUtilHelper.debug){
						Log.i(TAG,key + ":" + map.get(key));
					}
					parameters.add(new BasicNameValuePair(key, map.get(key)));  
				}
			}
			try {
				post.setEntity(new UrlEncodedFormEntity(parameters,HTTP.UTF_8));
				HttpResponse response = client.execute(post);
				if (response.getStatusLine().getStatusCode() == 200){
					resultData = EntityUtils.toString(response.getEntity());
				}
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} 
		}catch (Exception e) {
			// TODO: handle exception
		}

		return resultData;
	}
	
	/**
	 * 获取本应用程序的uid，用户统计本程序的流量
	 * @param context
	 * @return
	 */
	public static int getAppId(Context context){
		PackageManager pckMan = context.getPackageManager();
		List<PackageInfo> packs = pckMan.getInstalledPackages(0);
		int uid = 0;
		for (PackageInfo p:packs) {
			String name = p.applicationInfo.className;
			Log.i("ConfigUtilHelper","name:" + name);
			if((p.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM)==0&&  
					(p.applicationInfo.flags&ApplicationInfo.FLAG_UPDATED_SYSTEM_APP)==0){ 		
				int appid = p.applicationInfo.uid;
//				String name = p.applicationInfo.className;
//				Log.i("ConfigUtilHelper","name:" + name);
				if(name != null && name.equals("com.cmcc.aregister.MyApplication")){
					return appid;
				}
			}
		}
		return uid;
	}
	
	public static int getUids(Context context) {
		int uid = 1000;
		PackageManager pm = context.getPackageManager();
		List<PackageInfo> packinfos = pm
				.getInstalledPackages(PackageManager.GET_UNINSTALLED_PACKAGES
						| PackageManager.GET_PERMISSIONS);
		for (PackageInfo info : packinfos) {
			String[] premissions = info.requestedPermissions;
			if (premissions != null && premissions.length > 0) {
				for (String premission : premissions) {
					if ("android.permission.INTERNET".equals(premission)) {
						
						uid = info.applicationInfo.uid;
							Log.i("ConfigUtilHelper", "uid = " + uid);
						 String name = pm.getNameForUid(uid);
						 Log.i("ConfigUtilHelper","name:" + name);
						 if(name.equals("com.cmcc.aregister")){
							 return uid;
						 }
					}
				}
			}
		}
		return uid;
	}
	
	
	
	/*public static String getRelationText(int relation) {
        String txt = "";
        switch (relation) {
        case 1:
            txt = "本人";
            break;
        case 2:
            txt = "妻子";
            break;
        case 3:
            txt = "丈夫";
            break;
        case 4:
            txt = "儿女";
            break;
        case 5:
            txt = "孙子";
            break;
        case 6:
            txt = "爷爷";
            break;
        case 7:
            txt = "奶奶";
            break;
        }
        return txt;
    }*/
}
